﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Drawing.Imaging;

namespace WindowsFormsApplication2
{
    public class GanjiPic : BoundaryPostData
    {
        public GanjiPic(CookieCollection ck)
            : base(ck)
        {

        }
        public bool useCustom = true;
        public override string Referer
             {
                 get { 
                 
                 return  "http://sta.ganji.com/public/swf/swfupload-2.swf?4024";
                 }
           
        }
            
           
        private string _thumbHeight;
        public string thumbHeight
        {
            get
            {

                if (string.IsNullOrEmpty(_thumbHeight))
                {
                    return "75";
                }
                else
                {

                    return _thumbHeight;
                }
            }
            set
            {

                _thumbHeight = value;
            }
        }
        private bool? _createThumb;
        public bool createThumb
        {

            get
            {

                if (_createThumb.HasValue)
                {
                    return _createThumb.Value;
                }
                else
                {

                    return false;
                }
            }
            set
            {

                _createThumb = value;
            }
        }

        private string _thumbWidth;
        public string thumbWidth
        {

            get
            {
                if (string.IsNullOrEmpty(_thumbWidth))
                {
                    return "90";
                }
                else
                {
                    return _thumbWidth;
                }

            }
            set
            {


                _thumbWidth = value;
            }
        }

        public string minWidth = "0";

        private bool? _resizeImage;

        public bool resizeImage
        {


            get
            {

                if (_resizeImage.HasValue)
                {
                    return _resizeImage.Value;
                }
                else
                {

                    return true;
                }

            }
            set
            {

                _resizeImage = value;
            }
        }

        public string maxSize = "10485760";

        public string minHeight = "0";
        public string MAX_FILE_SIZE = "10485760";



        public bool? _thumbCutEnable;



        public bool thumbCutEnable
        {


            get
            {

                if (_thumbCutEnable.HasValue)
                {
                    return _thumbCutEnable.Value;
                }
                else
                {
                    return true;
                }
            }
            set
            {


                _thumbCutEnable = value;
            }
        }

        private bool? _resizeCutEnable;



        public bool resizeCutEnable
        {

            get
            {

                if (_resizeCutEnable.HasValue)
                {

                    return _resizeCutEnable.Value;
                }
                else
                {
                    return false;
                }

            }
            set
            {

                _resizeCutEnable = value;
            }

        }
        public string type = "jpg,jpeg,png,bmp";




        public string filename
        {
            get
            {

                return Path.GetFileName(this.FilePathStr);

            }

        }




        private string boundarySectionSpliter
        {

            get
            {

                ///return "--" + this.TicksStr;
                return "------WebKitFormBoundary" + this.TicksStr;

            }
        }
        public string uploadDir { get; set; }

        public string resizeWidth { get; set; }
        public string FilePathStr { get; set; }

        public string resizeHeight { get; set; }


        public string guid { get; set; }
        private string ContentDispositionFormat = "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
        public string GetContentDisposition(string name, string value)
        {
            return string.Format(ContentDispositionFormat, name, value).ToString();

        }
        public override string DoRequestPost(bool allowdir, string urla, string postdata)
        {
            
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(urla);

            req.CookieContainer = new CookieContainer();
            req.UserAgent = this.UserAgent;
            req.KeepAlive = true;
            if (!string.IsNullOrEmpty(this.Referer))
            {
                req.Referer = this.Referer;
            }
            // req.CookieContainer.Add(strCokAddColnew("ganji_uuid=5170713550418216074941; ganji_xuuid=a00bd1e8-8802-4d0f-8737-20af1e6f4f17; undefined=51fcc4f3-d030-4435-85e1-171248097f40; supercookie=AGL4AmLjAGtlWQyvMQL5BGV4MzZ2LJAwBQAzZQZlMwyvBTZlMQyyMJSzMGV3BTMvZTL%3D; 58uuid=a8a7d56c-88fd-46a0-872a-85a370f9b007; GANJISESSID=826e55f6ec397d421876d60eddeb9b76; sscode=ok%2FU3YcPpemPfJQPokXROutr; GanjiUserName=elingsoft123; GanjiUserInfo=%7B%22user_id%22%3A568760582%2C%22email%22%3A%22%22%2C%22username%22%3A%22elingsoft123%22%2C%22user_name%22%3A%22elingsoft123%22%2C%22nickname%22%3A%22%22%7D; bizs=%5B%5D; last_name=elingsoft123; use_https=1; __utmt=1; STA_DS=1; nTalk_CACHE_DATA={uid:kf_10111_ISME9754_568760582}; NTKF_T2D_CLIENTID=guestA308F3D1-01E9-9234-6C4A-D489AC18228C; lg=1; _gl_speed=%5B%22%2Fpub%2Fpub_select.php%22%2C1447212909438%5D; citydomain=nb; __utma=32156897.1762231046.1444439497.1447203159.1447212544.14; __utmb=32156897.3.10.1447212544; __utmc=32156897; __utmz=32156897.1447212544.14.8.utmcsr=ganji.com|utmccn=(referral)|utmcmd=referral|utmcct=/vip/my_post_list.php; _gl_tracker=%7B%22ca_source%22%3A%22-%22%2C%22ca_name%22%3A%22-%22%2C%22ca_kw%22%3A%22-%22%2C%22ca_id%22%3A%22-%22%2C%22ca_s%22%3A%22self%22%2C%22ca_n%22%3A%22-%22%2C%22ca_i%22%3A%22-%22%2C%22sid%22%3A31958504601%7D", ".ganji.com", new CookieCollection()));
           // req.CookieContainer.Add(strCokAddColnew("ganji_uuid=5170713550418216074941; ganji_xuuid=a00bd1e8-8802-4d0f-8737-20af1e6f4f17; undefined=51fcc4f3-d030-4435-85e1-171248097f40; supercookie=AGL4AmLjAGtlWQyvMQL5BGV4MzZ2LJAwBQAzZQZlMwyvBTZlMQyyMJSzMGV3BTMvZTL%3D; 58uuid=a8a7d56c-88fd-46a0-872a-85a370f9b007; use_https=1; NTKF_T2D_CLIENTID=guestA308F3D1-01E9-9234-6C4A-D489AC18228C; lg=1; citydomain=nb; GANJISESSID=055f2470e9813fe2e1c8451deeaeb8e3; sscode=ok%2FU3YcPpemPfJQPokXROutr; GanjiUserName=elingsoft123; GanjiUserInfo=%7B%22user_id%22%3A568760582%2C%22email%22%3A%22%22%2C%22username%22%3A%22elingsoft123%22%2C%22user_name%22%3A%22elingsoft123%22%2C%22nickname%22%3A%22%22%7D; bizs=%5B%5D; last_name=elingsoft123; __utmt=1; __utma=32156897.1954574302.1447230154.1447230154.1447289562.2; __utmb=32156897.4.10.1447289562; __utmc=32156897; __utmz=32156897.1447230154.1.1.utmcsr=nb.ganji.com|utmccn=(referral)|utmcmd=referral|utmcct=/tool/uploader2/; _gl_tracker=%7B%22ca_source%22%3A%22-%22%2C%22ca_name%22%3A%22-%22%2C%22ca_kw%22%3A%22-%22%2C%22ca_id%22%3A%22-%22%2C%22ca_s%22%3A%22self%22%2C%22ca_n%22%3A%22-%22%2C%22ca_i%22%3A%22-%22%2C%22sid%22%3A31961930558%7D", ".ganji.com", new CookieCollection()));
            //req.Headers.Add("X-Requested-With", "ShockwaveFlash/19.0.0.186");
              req.CookieContainer.Add(cklist);

            if (this.wp != null)
            {
                req.Proxy = wp;
            }

            req.AllowAutoRedirect = allowdir;

            string responseData = String.Empty;
            req.Method = "POST";

            req.Accept = this.Accept;
            //   req.ContentType = "multipart/form-data; boundary=" + this.TicksStr;
            if (useCustom)
            {
                req.ContentType = "multipart/form-data; boundary=----WebKitFormBoundary" + this.TicksStr;
            }
            else
            {
                req.ContentType = "multipart/form-data; boundary=----WebKitFormBoundaryVms98WyQk7DpItTe";

            }
            using (Stream reqStream = req.GetRequestStream())
            {

                if (useCustom)
                {
                    StringBuilder sb = new StringBuilder();

                    //sb.Append("\r\n\r\n");
                    //sb.Append("Referer: " + this.Referer+"\r\n");
                    //sb.Append("Content-type:" + "multipart/form-data; boundary=" + this.TicksStr);

                    //sb.Append("\r\n\r\n");
                    sb.Append(boundarySectionSpliter);

                    sb.Append(GetContentDisposition("thumbHeight", thumbHeight));
                    sb.Append(boundarySectionSpliter);

                    sb.Append(GetContentDisposition("createThumb", createThumb.ToString().ToLower()));
                    sb.Append(boundarySectionSpliter);

                    sb.Append(GetContentDisposition("thumbWidth", thumbWidth));

                    sb.Append(boundarySectionSpliter);
                    sb.Append(GetContentDisposition("minWidth", minWidth));
                    sb.Append(boundarySectionSpliter);
                    sb.Append(GetContentDisposition("resizeImage", resizeImage.ToString().ToLower()));
                    sb.Append(boundarySectionSpliter);
                    sb.Append(GetContentDisposition("maxSize", maxSize));
                    sb.Append(boundarySectionSpliter);

                    sb.Append(GetContentDisposition("minHeight", minHeight));
                    sb.Append(boundarySectionSpliter);

                    sb.Append(GetContentDisposition("MAX_FILE_SIZE", MAX_FILE_SIZE));


                    sb.Append(boundarySectionSpliter);

                    sb.Append(GetContentDisposition("uploadDir", uploadDir));
                    sb.Append(boundarySectionSpliter);

                    sb.Append(GetContentDisposition("resizeWidth", resizeWidth));
                    sb.Append(boundarySectionSpliter);
                    sb.Append(GetContentDisposition("thumbCutEnable", thumbCutEnable.ToString().ToLower()));
                    sb.Append(boundarySectionSpliter);

                    sb.Append(GetContentDisposition("resizeCutEnable", resizeCutEnable.ToString().ToLower()));
                    sb.Append(boundarySectionSpliter);
                    sb.Append(GetContentDisposition("type", type));
                    sb.Append(boundarySectionSpliter);
                    sb.Append(GetContentDisposition("resizeHeight", resizeHeight));
                    sb.Append(boundarySectionSpliter);
                    sb.Append(GetContentDisposition("_guid", guid));
                    sb.Append(boundarySectionSpliter);
                    // sb.Append(string.Format("\r\nContent-Disposition: form-data; name=\"Filedata\"; filename=\"{0}\"\r\nContent-Type: application/octet-stream\r\n\r\n", filename));
                    sb.Append(string.Format("\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\nContent-Type: image/jpeg\r\n\r\n", filename));

                    byte[] bs = Encoding.UTF8.GetBytes(sb.ToString());

              

                   reqStream.Write(bs, 0, bs.Length);
                    //FileStream fileStream1 = new FileStream("C:\\123\\hd.txt", FileMode.Open);
                    //byte[] buffer1 = new Byte[(int)fileStream1.Length];
                    //int bytesRead1 = 0;
                    //while ((bytesRead1 = fileStream1.Read(buffer1, 0, buffer1.Length)) != 0)
                    //    reqStream.Write(buffer1, 0, bytesRead1);
                    //fileStream1.Close();
                    FileStream fileStream = new FileStream(this.FilePathStr, FileMode.Open);


                    byte[] buffer = new Byte[(int)fileStream.Length];
                    int bytesRead = 0;
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                        reqStream.Write(buffer, 0, bytesRead);

                    fileStream.Close();

                    byte[] bs2 = Encoding.UTF8.GetBytes("\r\n"+boundarySectionSpliter + "--");





                    reqStream.Write(bs2, 0, bs2.Length);
                }
                else
                {

                    FileStream fileStream = new FileStream("C:\\123\\a.txt", FileMode.Open);
                    byte[] buffer = new Byte[(int)fileStream.Length];
                    int bytesRead = 0;
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                        reqStream.Write(buffer, 0, bytesRead);
                }
                reqStream.Close();
            }


            HttpWebResponse res = (HttpWebResponse)req.GetResponse();

            using (Stream stream = res.GetResponseStream())
            {
                using (StreamReader streamReader = new StreamReader(stream))
                {
                    string msg = streamReader.ReadToEnd();
                     if (!string.IsNullOrEmpty(msg))
                     {
                         this.LastStatus = "上传图片成功";
                     }
                    int a = res.Cookies.Count;
                    if (a > 0)
                    {


                        cklist.Add(res.Cookies);
                    }
                    //    string lc = res.Headers["Location"].ToString();
                    return msg;
                }
            }

            return "";
        }

      
      
    }
}

